
package com.lzx.iteam.util;


import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.util.Log;
import com.google.protobuf.InvalidProtocolBufferException;
import com.lzx.iteam.contactssearch.conversion.Addressbook.Person;
import com.lzx.iteam.contactssearch.conversion.PinyinSearch;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 统一控制 Prefercen 配置文件 工具类
 * 
 * @author gaotong
 */
public class PreferenceUtil implements OnSharedPreferenceChangeListener, SharedPreferences {

    public static final String IS_FIRST_START ="first_started";

    public final static String DISPLAY_NAME_ONLY = "display_name_only";

    public final static String TEAM_SID = "team_sid";
    public final static String USER_PHONE = "user_phone";
    public final static String USER_PASS = "user_pass";

    // 是否显示头像key
    public final static String CONTACT_ISDISPLAYPHOTO = "displayphoto";

    // 键盘风格key
    public final static String CONTACT_KEYBOARD_STYLE = "keyboard_style";
    

    // 名单排序 key
    public final static String CONTACT_NAME_SORT = "name_sort";
    
    public final static String CONTACT_FONT_SIZE = "font_size";
    public final static String SHOW_TIMES_CONTACTED = "show_times_contacted";

    public final static String APPROVAL_GROUP_ID = "approval_group_id";
    public final static String ATTENDANCE_GROUP_ID = "attendance_group_id";
    public final static String WEEKLY_GROUP_ID = "weekly_group_id";
    public final static String SALARY_GROUP_ID = "salary_group_id";

    public final static String CITY_GROUP_TOTAL_COUNT = "city_group_total_count";
    public final static String LAST_NAME_TOTAL_COUNT = "last_name_total_count";
    // 5-31 heihei: no need to prompt the user 5-31
//    public final static String FIRST_DIAL_ALERT_WHEN_CLICK = "first_dial_alert_when_click";
    
    /**
     * 0 not set yet
     * 1 to show
     * 2 already set, not to show
     */
    public final static String FIRST_GUIDE_SHOW_WEIBO = "first_guide_show_weibo";
    public final static int SHOW_WEIBO_NOT_SET = 0;
    public final static int SHOW_WEIBO_TO_SHOW = 1;
    public final static int SHOW_WEIBO_SETTED = 2;
    
    public final static String MY_STATUS_SYNC_DISTURB = "my_status_sync_disturb";
    public final static String MY_STATUS_DISTURB = "my_status_disturb";
    public final static String MY_STATUS_SELECTED = "my_status_check";
    public final static String MY_STATUS = "my_status";
    public final static String MY_STATUS_ID = "my_status_id";
    public final static String NEED_WRITE_STATUS = "need_write_status";
        
    public final static String LONG_CLICK_DIAL = "quick_dial";

    public static final String LOCAL_CLOUD_RELATIONSHIP_READY = "local_cloud_relationship_ready";
    public static final String CLOUD_ID_2_CONTACT_ID = "cloud_id_2_contact_id";
    public static final String CLOUD_REGIST_USER = "regist_user";
    public static final String CLOUD_PHONE_2_USEID = "cloud_phone_2_useid";
    public static final String CONTACT_ID_2_CLOUD_ID = "contact_id_2_cloud_id";
    public static final String CONTACT_ID_2_DIST_STATUS = "contact_id_2_dist_status";
    public static final String CONTACT_ID_2_TEXT_STATUS = "contact_id_2_text_status";
    
    // 是否有按键音
    public final static String CONTACT_IS_HAVESOUND = "ishavesound";

    // 键盘左右锁定
    public final static String CONTACT_IS_KEYBOARDLOCK = "iskeyboardlock";

    // 通话后是否返回拨号精灵
    public final static String CONTACT_IS_CALLBACKTOAPP = "iscallback_to_app";

    // 是否扔出去打
    public final static String CONTACT_IS_THROWCALL = "isthrow_call";
    
    public final static String CALL_CONNECT_VIBRATE = "connect_vibrate";
    
    public final static String FLOAT_WINDOW = "float_window";
    

    public final static String HANGUP = "hangup";
    
    public final static String ISREDIAL = "isredial";

    public final static String SHOW_PEOPLE_NO_PHONENUMBER = "show_people_withphonenumber";

    public final static String CALL_HANGUP_VIBRATE = "hangup_vibrate";

    // ip call
    public final static String CONTACT_IPCALL = "ip_call";
    
    public final static String CONTACT_IPCALL2 = "ip_call2";
    
    public final static String CONTACT_IPCALL_POSTFIX = "ip_call_postfix";
    
    public final static String CONTACT_IPCALL_POSTFIX2 = "ip_call_postfix2";

    // 城市区号前缀  如北京区号10  国内非北京拨打北京固定电话时应该拨 “010********”  中国的precity_code是“0”
    public final static String CONTACT_PRECITY_CODE = "pre_city_code";
    
    // 国家通信码  如中国 86     香港 852     
    public final static String CONTACT_COUNTRY_CODE = "country_code";

    // 所在地国际冠码前缀  中国向香港拨打电话时  "00852*******"  中国的国际冠码是 “00”
    public final static String CONTACT_INTERNATIONAL_PRFIX_CODE = "international_prefix_code";

    public final static String SETTING_INIT = "setting_init";
    
    // 键盘主题颜色
    public final static String CONTACT_KEYBOARD_THEMECOLOR = "keyboard_themecolor";
    
    //默认显示联系人还是CALLLOG
    public final static String CONTACT_SHOW_CONTENT = "show_content";

    // 键盘方向
    public final static String CONTACT_KEYBOARD_LAYOUTORIENTATION = "keyboard_layout_orientation";
    public final static String IS_T9 = "is_t9_vertial";// now we only use one key
    public final static String KEYPAD_AT_RIGHT = "keypad_at_right";

    public final static String INCOMING_CALL_2_SMS = "incoming_call_2_sms";
    public final static String INCOMING_CALL_2_SMS_TOGGLE = "incoming_call_2_sms_toggle";
    public final static String USE_STATUS_SMS = "use_status_sms";
    public final static String TIME_START_HOUR = "time_start_hour";
    public final static String TIME_START_MINUTE = "time_start_minute";
    public final static String TIME_STOP_HOUR = "time_stop_hour";
    public final static String TIME_STOP_MINUTE = "time_stop_minute";
    public final static String VIP_GROUP_MODE = "vip_group_mode";
    public final static String VIP_GROUP_GROUP_IDS = "vip_group_group_ids";
    public final static String TIME_SPINNER_SELECTED = "time_spinner_selected";
    public final static String TIME_EXPIRED = "time_expired";
    public final static int VIP_GROUP_USER_GROUP = 1000;
    public final static int VIP_GROUP_EVERYBODY_BLOCK = 1001;
    public final static int VIP_GROUP_ALL_CONTACTS = 1002;
    public final static int VIP_GROUP_EVERYBODY = 1003;
    
    public final static String EMERGENCY_MODE_TOGGLE = "emergency_mode_toggle";
    
    public final static String SMS_FORWORD = "sms_forword";
    public final static String SMS_FORWORD_TOGGLE = "sms_forword_toggle";
    
    public final static String ROAMING_CALL_BACK_TOGGLE = "roaming_call_back_toggle";
    
    // 名片相关设置保存
//    public final static String NAMECARD_CONTACTNAME = "contactname";

    public final static String CONTACT_DELETE = "contact_deleted";
    public final static String CONTACT_INSERT = "contact_insert";
    public final static String CONTACT_UPDATE = "contact_updated";
    
    public final static String NAMECARD_CHANGED = "namecard_changed";
    public final static String NAMECARD_CONTACTID = "contactid";
    public final static String NAMECARD_AVATAR = "avatar";
    public final static String CLIENT_USEID = "useid";
    public final static String CLIENT_SECURITY_KRY = "security_key";
    public final static String CONTACT_NUMBERS = "contact_numbers";

    public final static String SHARECARD_CONTACTID = "share_contactid";

    public static final String HOST_NAME = "hostname";
    
    public static final String SHARE_POLICY = "sharepolicy";

    public static final String NAME_CARD_NUMBER = "bitset";
    
    public static final String SYNC_UP_OVER = "synupFlag";
    
    public static final String LAST_RUN_VERSIONCODE= "lastRunVersionCode";
    
    public static final String CONTACT_ON_SDCARD = "contact_on_sdcard";
    
    public static final String USER_ID = "user_id";
    
    public static final String LATEST_VERSION = "latest_version";
    
    public static final String LATEST_VERSION_SCHEDULE = "latest_version_schedule";
    
    //business card received
    public static final String CARD_RECEIVED = "card_received";
    
    public static final String PERSISTED_CONTACT_ID = "all_persist_contactId";
    
    //黑名单相关
    public static final String BLOCK_MODE = "blockmode";
    public static final String GROUP_MODE = "group_mode";
    public static final String GROUP_SELECTED_CITY = "group_selected_city";
    public static final String GROUP_SELECTED_NAME = "group_selected_name";
    public static final String GROUP_SELECTED_GROUP = "group_selected_group";

    //搜索相关
    public static final String FIRST_LETTER_STRING = "firstletterarray";
    
    public static final String HANZI_PINYIN = "hanziPinyin";
    
    public static final String IS_TWO_SIM = "istwosim";
    
    public static final String TWO_SIM_MODEL = "twosimmodel";
    
    public static final String TWO_SIM_TYPE = "twosimtype";
    
    public static final String TWO_SIM_FACTORY = "twosimfactory";
    
    public static final String TWO_SIM_PACKAGE = "twosimpackage";
    
    public static final String TWO_SIM_DWONLOAD_URL = "twosimdownloadurl";
    

    private final String TAG = "PreferenceUtil";

    private Context mContext;

    private SharedPreferences mPreference;
    
    private SharedPreferences mCloudObjectPreference;
    
    private SharedPreferences mObjectPreference;

    private static String CONFIGFILENAME = "config";

    private final static int INTEGER_CLASSNAME = 0;

    private final static int LONG_CLASSNAME = 1;

    private final static int FLOAT_CLASSNAME = 2;

    private final static int BOOLEAN_CLASSNAME = 3;

    private final static int STRING_CLASSNAME = 4;

    public static final String CONTACT_KEYBOARD_PACKAGENAME = "keyboard_packagename";

    private Map<String, Integer> maptypes = new HashMap<String, Integer>();

    // for thread-safe
    private ConcurrentHashMap<String, ArrayList<OnSharedPreferenceChangeListener>> mListenerForKey;

    private static PreferenceUtil sPreferenceUtil;
    
    private static String OBJECT_FILE_NAME = "contacts";
    
    private static String CLOUD_2_CONTACT_FILE = "cloud_2_contact_file";
    
    public static final String TX_WEIBO_TOKEN = "tx_weibo_token";
    
    public static final String TX_WEIBO_SECRET = "tx_weibo_secret";
    
    public static final String CLOUD_GROUP_TYPE = "cloud_group_type";
    
    public static final String CLEAR_TIME = "clear_time";

    public static final String SMS_RECIVE = "sms_recive";

    public static final String MULTI_CALL_FLAG = "multi_call_flag";
    public static final String NORMAL_CALL_FLAG = "normal_call_flag";
    public static final String NORMAL_CALL_FLAG_SC = "normal_call_flag_sc";
    public static final String END_CALL_MESSAGE = "end_call_message";
    public static final String SESSION_ID = "session_id";
    public static final String CALL_STATUS = "call_status";


    public static final String CUSTOM_EVENT = "custom_event";

    //推送业务类型
    public static final String PUSH_CODE = "pushCode";

    //竖键盘最后坐标(top)
    public static final String VERTICAL_KEYBOARD_LAST_TOP = "verticalBoardLastTop";
    //横键盘最后坐标(left)
    public static final String HORI_KEYBOARD_LAST_LEFT = "horiBoardLastLeft";

    public synchronized static PreferenceUtil getInstance(Context context) {
        if (sPreferenceUtil == null) {
            sPreferenceUtil = new PreferenceUtil(context);
        }
        return sPreferenceUtil;
    }
    
     private PreferenceUtil(Context context) {
        mContext = context;
        
        /*mPreference = mContext.getSharedPreferences(CONFIGFILENAME,
                0x0004);*/
         mPreference = mContext.getSharedPreferences(CONFIGFILENAME,Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE
                 + Context.MODE_MULTI_PROCESS);
        
        mPreference.registerOnSharedPreferenceChangeListener(this);
        maptypes.put(Integer.class.getName(), INTEGER_CLASSNAME);
        maptypes.put(Long.class.getName(), LONG_CLASSNAME);
        maptypes.put(Float.class.getName(), FLOAT_CLASSNAME);
        maptypes.put(Boolean.class.getName(), BOOLEAN_CLASSNAME);
        maptypes.put(String.class.getName(), STRING_CLASSNAME);
        
        mListenerForKey = new ConcurrentHashMap<String, ArrayList<OnSharedPreferenceChangeListener>>();
        
    }

    public SharedPreferences getPreference() {
        return mPreference;
    }

    public void removeInLocalGroup(String gid) {
        String idStr = getGidStr();
        String[] idArr = idStr.split(",");
        
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < idArr.length; i++) {
            if (!idArr[i].equals(gid)) {
                sb.append(idArr[i]).append(',');
            }
        }
        
        saveGidStr(sb.toString());
    }
    
    /**
     * ICS not support Context.MODE_MULTI_PROCESS of SharedPreferences any more
     */
    public void saveGidStr(String gidStr) {
        File f = new File(mContext.getFilesDir(), "local_gid");
        if (!f.exists()) {
            try { f.createNewFile(); } 
            catch (IOException e) { e.printStackTrace(); return;}
        }
        
        FileWriter fw = null;
        try {
            fw = new FileWriter(f);
            fw.write(gidStr);
            fw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fw != null) 
                try { fw.close();} 
                catch (IOException e) { e.printStackTrace(); }
        }
    }
    
    public void clearLocalGid() {
        File f = new File(mContext.getFilesDir(), "local_gid");
        if (f.exists()) f.delete();
    }
    
    public String getGidStr() {
        File f = new File(mContext.getFilesDir(), "local_gid");
        if (!f.exists()) {
            return "";
        }
        
        StringBuilder sb = new StringBuilder();
        FileReader fw = null;
        try {
            fw = new FileReader(f);
            int count = -1;
            char[] bc = new char[100];
            while ((count = fw.read(bc)) != -1) {
                sb.append(bc, 0, count);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fw != null) 
                try { fw.close();} 
                catch (IOException e) { e.printStackTrace(); }
        }
        
        return sb.toString();
    }
    
    /**
     * 根据输入参数obj的类型选择插入
     * 
     * @param key
     * @param obj
     * @return
     */
    public boolean save(String key, Object obj) {

        boolean result = false;
        Editor edit = mPreference.edit();

        if (obj instanceof Integer) {
            edit.putInt(key, (Integer) obj);
        } else if (obj instanceof Long) {
            edit.putLong(key, (Long) obj);
        } else if (obj instanceof Float) {
            edit.putFloat(key, (Float) obj);
        } else if (obj instanceof Boolean) {
            edit.putBoolean(key, (Boolean) obj);
        } else if (obj instanceof String) {
            edit.putString(key, (String) obj);
        } else {
            Log.e(TAG, "Editor put error");
        }

        // 有些机型会出现 StackOverflowError htc G6
        try {
            result = edit.commit();
        } catch (StackOverflowError error) {
            Log.e(TAG, "save: " + error.getMessage());
        }
        return result; 
    }
    
    public void clearAll() {
        Editor edit = mPreference.edit();
        edit.clear();
        edit.commit();
        
        ensurePreference();
        Editor objectEditor = mObjectPreference.edit();
        objectEditor.clear();
        objectEditor.commit();
    }
    
    public void clearObjectAll() {
        
        ensurePreference();
        Editor objectEditor = mObjectPreference.edit();
        objectEditor.clear();
        objectEditor.commit();
    }

    /**
     * 根据输入参数obj的类型选择插入
     * 
     * @param key
     * @param obj
     * @return
     */
    public boolean delete(String key) {
        Editor edit = mPreference.edit();
        edit.remove(key);
        return edit.commit();
    }

    /**
     * 根据key 和 数据类型获取value
     * 
     * @param key
     * @param classtype
     * @return 要求使用人员必须知道获取配置项的数据类型
     */
    public <T> T get(String key, Class<T> classtype) {

        String classname = classtype.getName();
        Integer type = maptypes.get(classname);
        Object result = null;

        if (type != null) {

            switch (type) {
                case INTEGER_CLASSNAME:
                    result = mPreference.getInt(key, 0);
                    break;
                case LONG_CLASSNAME:
                    result = mPreference.getLong(key, 0);
                    break;
                case FLOAT_CLASSNAME:
                    result = mPreference.getFloat(key, 0);
                    break;
                case BOOLEAN_CLASSNAME:
                    result = mPreference.getBoolean(key, false);
                    break;
                case STRING_CLASSNAME:
                    result = mPreference.getString(key, "");
                    break;

                default:
                    break;
            }
        }

        return (T) result;

    }

    public void registerOnSharedPreferenceChangeListener(String key,
            OnSharedPreferenceChangeListener listener) {
        ArrayList<OnSharedPreferenceChangeListener> arrayList = mListenerForKey.get(key);
        if (arrayList != null) {
            arrayList.add(listener);
        } else {
            arrayList = new ArrayList<OnSharedPreferenceChangeListener>();
            arrayList.add(listener);
            mListenerForKey.put(key, arrayList);
        }
    }

    public void unregisterOnSharedPreferenceChangeListener(String key, OnSharedPreferenceChangeListener listener) {
        ArrayList<OnSharedPreferenceChangeListener> arrayList = mListenerForKey.get(key);
        if (arrayList != null) {
            arrayList.remove(listener);
        } 
    }

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        ArrayList<OnSharedPreferenceChangeListener> arrayList = mListenerForKey.get(key);
        if (arrayList == null) return;
        Iterator<OnSharedPreferenceChangeListener> it = arrayList.iterator();
        while (it.hasNext()) {
            OnSharedPreferenceChangeListener listener = it.next();
            listener.onSharedPreferenceChanged(sharedPreferences, key);
        }
    }

    @Override
    public boolean contains(String key) {
        if (mPreference.contains(key))
            return true;
        return false;
    }

    @Override
    public Editor edit() {
        return mPreference.edit();
    }

    @Override
    public Map<String, ?> getAll() {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean getBoolean(String key, boolean defValue) {
        return mPreference.getBoolean(key, defValue);
    }

    @Override
    public float getFloat(String key, float defValue) {
        return mPreference.getFloat(key, defValue);
    }

    @Override
    public int getInt(String key, int defValue) {
        return mPreference.getInt(key, defValue);
    }

    @Override
    public long getLong(String key, long defValue) {
        return mPreference.getLong(key, defValue);
    }

    @Override
    public String getString(String key, String defValue) {
        return mPreference.getString(key, defValue);
    }

    @Override
    public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {

    }

    @Override
    public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {
        
    }
    
    public void saveObject(String key, Object val) {
        
        String ret = StringUtil.stringWithObject(val);
        if (!ret.equals("")) {
            save(OBJECT_FILE_NAME, key, ret);
        }
    }
    
    public void registerCloudContactListener(OnSharedPreferenceChangeListener listener) {
        ensureCloudPreference();
        mCloudObjectPreference.registerOnSharedPreferenceChangeListener(listener);
    }
    
    public void unregisterCloudContactListener(OnSharedPreferenceChangeListener listener) {
        ensureCloudPreference();
        mCloudObjectPreference.unregisterOnSharedPreferenceChangeListener(listener);
    }
    
    
    public void saveCloudContact(String key, Object val) {
        
        String ret = StringUtil.stringWithObject(val);
        if (!ret.equals("")) {
            ensureCloudPreference();
            Editor editor = mCloudObjectPreference.edit();
            try {
                editor.putString(key, ret);
                editor.commit();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public Object getCloudContact(String key) {
        String ret = getCloudObject(key);
        if (ret.equals("")) {
            return null;
        } else {
            return StringUtil.objectWithString(ret);
        }
    }

    private void ensureCloudPreference() {
        if (mCloudObjectPreference == null) {
            mCloudObjectPreference = mContext.getSharedPreferences(CLOUD_2_CONTACT_FILE,
                    Activity.MODE_PRIVATE);
        }
    }

    private String getCloudObject(String key) {
        ensureCloudPreference();
        String str = mCloudObjectPreference.getString(key, "");
        return str;
    }

    public void delCloudContact() {
        ensureCloudPreference();
        Editor editor = mCloudObjectPreference.edit();
        editor.clear();
        editor.commit();
    }

    public void saveByteArray(String key, byte[] value) {
        save(OBJECT_FILE_NAME, key, value.toString());
    }

    public void saveObjectSring(String key, String value) {
        save(OBJECT_FILE_NAME, key, value);
    }

    public String getByteArray(String key) {
        return get(OBJECT_FILE_NAME, key);
    }

    public Person getPerson(long contactId) {
        String personString = getByteArray(Long.toString(contactId));
        Person person = null;
        try {
            if (!StringUtil.isEmpty(personString)) {
                byte[] array = Base64.decode(personString, Base64.NO_WRAP);
                person = Person.parseFrom(array);
            }
        } catch (InvalidProtocolBufferException e) {
        } catch (IllegalArgumentException e) {
//            e.printStackTrace();
        }

        return person;
    }

    public Person getPerson(String contactId) {
        String personString = getByteArray(contactId);
        Person person = null;
        try {
            if (!StringUtil.isEmpty(personString)) {
                byte[] array = Base64.decode(personString, Base64.NO_WRAP);
                person = Person.parseFrom(array);
            }
        } catch (InvalidProtocolBufferException e) {
        } catch (IllegalArgumentException e) {
//            e.printStackTrace();
        }

        return person;
    }
    public void deletePerson(long contactId)
    {
        String key = Long.toString(contactId);
        //获得SharedPreferences对象
        SharedPreferences MyPreferences = mContext.getSharedPreferences(OBJECT_FILE_NAME, Activity.MODE_PRIVATE);
        if(MyPreferences!=null)
        {
            //获得SharedPreferences.Editor对象
            Editor editor = MyPreferences.edit();
            editor.remove(key);
            editor.commit();
        }
    }

    public void deletePerson(String contactId)
    {
        //获得SharedPreferences对象
        SharedPreferences MyPreferences = mContext.getSharedPreferences(OBJECT_FILE_NAME, Activity.MODE_PRIVATE);
        if(MyPreferences!=null)
        {
            //获得SharedPreferences.Editor对象
            Editor editor = MyPreferences.edit();
            editor.remove(contactId);
            editor.commit();
        }
    }

    public void savePerson(long contactId, Person person) {
        String result = Base64.encodeToString(person.toByteArray(), Base64.NO_WRAP);
        if (getPerson(contactId) != null) {
            deletePerson(contactId);
        }
        save(OBJECT_FILE_NAME, Long.toString(contactId), result);
    }

    public void savePerson(long contactId, PinyinSearch.ContactInPersist memory) {

        Person.Builder builder = Person.newBuilder();
        if (memory.fullName == null) {
            memory.fullName = "";
        }
        builder.setDisplayName(memory.fullName);
        builder.setPhotoId(memory.photoId);
        builder.setRawId(memory.rawId);
        if (memory.organization == null) {
            memory.organization = "";
        }
        builder.setOrganization(memory.organization);

        if (memory.email == null) {
            memory.email = "";
        }
        builder.setEmail(memory.email);

        if (memory.fuzzyString == null) {
            memory.fuzzyString = "";
        }
        builder.setFuzzyString(memory.fuzzyString);

        builder.setContactedNumber(memory.contactedNumber);
        builder.setVersion(memory.version);

        if (memory.phoneNumber != null) {
            ArrayList<String> phoneNumber = memory.phoneNumber;
            for (String phoneElement : phoneNumber) {
                if (!StringUtil.isEmpty(phoneElement)) {
                    builder.addPhone(Person.PhoneNumber.newBuilder().setNumber(phoneElement));
                }
            }
        }

        if (memory.phoneNumberArea != null) {
            ArrayList<String> phoneNumberArea = memory.phoneNumberArea;
            for (String areaElement : phoneNumberArea) {
                if (!StringUtil.isEmpty(areaElement)) {
                    builder.addPhoneNumberArea(Person.PhoneNumberArea.newBuilder().setArea(
                            areaElement));
                }
            }
        }

        if (memory.groupIdSet != null) {
            HashSet<Long> hashIdSet = memory.groupIdSet;
            Iterator<Long> it = hashIdSet.iterator();
            while (it.hasNext()) {
                Long groupId = it.next();
                builder.addGroupIdSet(Person.GroupIdSet.newBuilder().setGroupId(groupId));
            }
        }
//        builder.build();
        Person person = builder.build();
        String str = person.toString();
        try {
            Person test = Person.parseFrom(str.getBytes());
            if (test != null) {
            }
        } catch (InvalidProtocolBufferException e) {
            // Auto-generated catch block
            e.printStackTrace();
        }
//        String result = new String(person.toByteArray());
        String result = Base64.encodeToString(person.toByteArray(), Base64.NO_WRAP);
        save(OBJECT_FILE_NAME, Long.toString(contactId), result);
    }

    /*public ContactInPersist deSerializationObj (String memoryStr) {

        ContactInPersist memory = new ContactInPersist();
        try {
            Person person = Person.parseFrom(memoryStr.getBytes());
            memory.fullName = person.getDisplayName();
            memory.photoId = person.getPhotoId();
            memory.rawId = person.getRawId();
            memory.organization = person.getOrganization();
            memory.email = person.getEmail();
            memory.fuzzyString = person.getFuzzyString();
            memory.contactedNumber = person.getContactedNumber();
            memory.version = person.getVersion();

            List<PhoneNumber> phoneList = person.getPhoneList();
            memory.phoneNumber = new ArrayList<String>();
            for (PhoneNumber phoneSub : phoneList) {
                memory.phoneNumber.add(phoneSub.getNumber());
            }

            List<Person.PhoneNumberArea> phoneNumberAreaList = person.getPhoneNumberAreaList();
            memory.phoneNumberArea = new ArrayList<String>();
            for (Person.PhoneNumberArea phoneAreaSub : phoneNumberAreaList) {
                memory.phoneNumberArea.add(phoneAreaSub.getArea());
            }

            List<Person.GroupIdSet> groupIdSet = person.getGroupIdSetList();
            memory.groupIdSet = new HashSet<Long>();
            for (Person.GroupIdSet groupId : groupIdSet) {
                memory.groupIdSet.add(groupId.getGroupId());
            }
        } catch (InvalidProtocolBufferException e) {
            // Auto-generated catch block
            e.printStackTrace();
        }

        return memory;
    }*/

    private void ensurePreference () {
        if (null == mObjectPreference) {
            mObjectPreference = mContext.getSharedPreferences(OBJECT_FILE_NAME, Activity.MODE_PRIVATE);
        }
    }

    public boolean containsObject(String key) {
        ensurePreference();
        if (mObjectPreference.contains(key)) {
            return true;
        }
        return false;
    }

    private void save(String name, String key, String val) {
        ensurePreference();
        Editor editor = mObjectPreference.edit();
        // 保存组件中的值
        try {
            editor.putString(key, val);
            editor.commit();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Object getObject(String key) {

        String ret = get(OBJECT_FILE_NAME, key);
        if (ret.equals("")) {
            return null;

        } else {
            return StringUtil.objectWithString(ret);
        }
    }

    public String get(String name, String key) {
        ensurePreference();
        String str = mObjectPreference.getString(key, "");
        return str;
    }

    public void delObject(String key)
    {
        //获得SharedPreferences对象
        SharedPreferences MyPreferences = mContext.getSharedPreferences(OBJECT_FILE_NAME, Activity.MODE_PRIVATE);
        if(MyPreferences!=null)
        {
            //获得SharedPreferences.Editor对象
            Editor editor = MyPreferences.edit();
            editor.remove(key);
            editor.commit();
        }
    }

    public Set<String> getStringSet(String arg0, Set<String> arg1) {

        return null;
    }


}
